<template>
  <div class="cmp-qrcode-previewer">
    <div class="qrcode-wrapper" v-if="qrcodeVisible">
      <div
        class="qrcode-inner"
        :key="'qrcode-body' + idx"
        v-for="(item, idx) in (qrcodeTextContent[pageIndex] &&
          qrcodeTextContent[pageIndex].text) ||
        []"
      >
        <h3>{{ qrcodeTextContent[pageIndex].name }}</h3>

        <svg-icon
          icon-class="last"
          v-if="pageIndex != 0"
          @click="lastPage()"
          class-name="iconsvg-preview"
        ></svg-icon>

        <svg-icon
          icon-class="right"
          v-if="pageIndex != qrcodeTextContent.length - 1"
          @click="nextPage()"
          class-name="iconsvg-next"
        ></svg-icon>

        <svg-icon
          icon-class="close"
          class-name="iconsvg-close"
          @click="toggleQRCode()"
        ></svg-icon>

        <div class="qrcode-body">
          <canvas
            :style="{ padding: imgScaleToPx + 'px' }"
            id="canvas"
            style="height: 480px"
            v-if="item"
          ></canvas>
        </div>
        <div class="qrcode-bottom">
          <template v-if="item">
            <el-checkbox
              size="medium"
              v-if="qrConfig.showTextbar === true"
              v-model="showTitle"
              @change="changShowTitle()"
            >
              是否显示标题
            </el-checkbox>
            <span class="zoom-bar">
              <i class="el-icon-zoom-in" @click="scaleImg(true)"></i>
              <i class="el-icon-zoom-out" @click="scaleImg(false)"></i>
            </span>
            <div class="qrcode-text" v-if="qrConfig.showTextbar === true">
              <b>
                {{
                  showTitle && idx == 0
                    ? qrcodeTextContent[pageIndex].name + ':'
                    : ''
                }}
              </b>
              <span class="qrcode-text-content" v-html="item"></span>
            </div>
          </template>
          <template>
            <div class="none-data" v-if="!item">数据为空</div>
          </template>
          <div style="text-align: center; padding: 20px 24px 10px">
            <el-button type="danger" @click="toggleQRCode">关闭</el-button>
            <el-button type="warning" @click="handleDownloadPicture(pageIndex)">
              下载
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import { nextTick } from 'vue'
  import { mapGetters } from 'vuex'
  // , mapMutations, mapActions
  // import { mapState } from 'vuex'
  var QRCode = require('qrcode')
  export default {
    name: 'QrcodePreviewer',
    data() {
      return {
        // qrcodeVisible: true,
        pageIndex: 0,
        imgScaleToPx: '0',
        showTitle: false,
        qrcodeVisible: false,
        qrcodeTextContent: [],
        qrConfig: {},
      }
    },
    computed: {
      ...mapGetters(['qrcodeShowData']),
    },
    watch: {
      qrcodeShowData: {
        handler: async function (val) {
          await nextTick()
          const { qrcodeVisible, qrcodeTextContent, config } = val
          this.qrcodeVisible = qrcodeVisible
          this.qrcodeTextContent = qrcodeTextContent
          this.qrConfig = config
          if (val.qrcodeTextContent.length > 0) this.changeQrCode(0)
        },
        immediate: true,
        deep: true,
      },
      // async qrcodeShowData(val) {
      // }
      // async qrcodeTextContent(val) {
      //   await nextTick()
      //   if
      //   this.changeQrCode(0)
      // },
    },
    methods: {
      changShowTitle() {},
      changeQrCode(index) {
        const { name, text } = this.qrcodeTextContent[index]
        let qrStr = text[0]
        if (this.showTitle) qrStr = name + ':' + qrStr
        this.toImage(qrStr)
      },
      toggleQRCode() {
        this.$store.dispatch('qrcode/setCloseQRCode')
      },
      scaleImg(max = true) {
        if (max) {
          if (this.imgScaleToPx <= 0) return
          this.imgScaleToPx = +this.imgScaleToPx - 20
        } else {
          if (this.imgScaleToPx > 100) return
          this.imgScaleToPx = +this.imgScaleToPx + 20
        }
      },
      lastPage() {
        if (this.pageIndex > 0) {
          this.pageIndex -= 1
          this.changeQrCode(this.pageIndex)
        }
      },
      nextPage() {
        if (this.pageIndex < this.qrcodeTextContent.length) {
          this.pageIndex += 1
          this.changeQrCode(this.pageIndex)
        }
      },
      async toImage(qrCodeText) {
        await nextTick()
        let canvas = document.querySelector('#canvas')
        QRCode.toCanvas(
          canvas,
          qrCodeText,
          {
            errorCorrectionLevel: 'L',
            width: 480,
            // version: 1,
            margin: 2,
          },
          function (error) {
            if (error) {
              console.trace(error)
              return
            }
          }
        )
      },
      async handleDownloadPicture(index) {
        const { name, text } = this.qrcodeTextContent[index]
        let qrStr = text[0]
        const self = this
        await nextTick()
        QRCode.toDataURL(qrStr, function (err, url) {
          // console.log(url)
          self.downloadFile(url, '用户的二维码')
        })
      },
      downloadFile(content, fileName) {
        //下载base64图片
        var base64ToBlob = function (code) {
          let parts = code.split(';base64,')
          let contentType = parts[0].split(':')[1]
          let raw = window.atob(parts[1])
          let rawLength = raw.length
          let uInt8Array = new Uint8Array(rawLength)
          for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i)
          }
          return new Blob([uInt8Array], {
            type: contentType,
          })
        }
        let aLink = document.createElement('a')
        let blob = base64ToBlob(content) //new Blob([content]);
        let evt = document.createEvent('HTMLEvents')
        //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
        evt.initEvent('click', true, true)
        aLink.download = fileName
        aLink.href = URL.createObjectURL(blob)
        aLink.click()
      },
    },
  }
</script>
<style lang="scss" scoped>
  .cmp-qrcode-previewer {
    display: inline-block;
    vertical-align: top;
    position: fixed;
    z-index: 10000;

    .iconsvg-close {
      position: absolute;
      right: 8px;
      top: 8px;
      width: 24px;
      height: 24px;
      fill: #8c8c8c;
      padding: 0;
      border-radius: 24px;
      z-index: 9999;
      cursor: pointer;
    }

    .qrcode-wrapper {
      position: fixed;
      display: flex;
      justify-content: space-around;
      align-items: center;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.2);
      z-index: 1000;

      .qrcode-inner {
        position: relative;
        border: 2px solid #fff;
        background-color: #fff;
        border-radius: 8px;
        width: 490px;

        .iconsvg-preview,
        .iconsvg-next {
          width: 48px;
          height: 48px;
          fill: #666;
          position: absolute;
          top: 50%;
          margin-top: -24px;

          &:hover {
            fill: #333;
          }
        }

        h3 {
          text-align: center;
          line-height: 16px;
          margin-top: 12px;
        }

        .iconsvg-preview {
          left: -72px;
        }

        .iconsvg-next {
          right: -72px;
        }
      }

      .qrcode-body {
        padding: 0px;
        overflow: hidden;
        margin: 0 auto;

        canvas {
          box-sizing: border-box;
          overflow: scroll;
        }

        img {
          width: 100%;
          height: 100%;
          display: block;
        }
      }

      .qrcode-bottom {
        padding: 0 16px 24px;

        .zoom-bar {
          float: right;

          i {
            cursor: pointer;

            &:hover {
              color: #409eff;
            }

            & + i {
              margin-left: 12px;
            }

            font-size: 24px;
          }
        }
      }

      .qrcode-text {
        display: block;
        padding: 8px;
        margin-top: 6px;
        background-color: #eee;
        max-height: 80px;
        overflow: auto;
        font-size: 12px;
        line-height: 1.3;
        word-break: break-word;
      }

      .qrcode-text-content {
        white-space: pre-line;
      }

      .qrcode-pic {
        // display: none;
        position: absolute;
        // visibility: hidden;
        // left: -10000px;
        // top: -10000px;
        top: 0;
        left: 0;
        padding: 20px;
        background-color: #fff;
        z-index: -99;

        // opacity: 0;
        .qrcode-content {
          /* display: flex;
        justify-content: space-between;
        align-items: flex-start; */
          padding: 0 24px;
          text-align: center;

          .top {
            /* width: 170px; 
          height: 170px; */
            margin: 0 auto;
            // background-color: red;
          }

          .bottom {
            /* flex: 1;
          margin-left: 20px; */
            margin-top: 25px;
            line-height: 1.5;
            font-size: 26px;
            text-align: left;
          }
        }

        .features {
          .title {
            margin: 35px 0;
            font-size: 20px;
            text-align: center;
          }

          .items {
            .item {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 10px 50px;
              margin-right: 24px;
              margin-left: 24px;
              box-shadow: 0px 0px 10px #aaa;
              border-radius: 5px;
            }

            .imgs {
              display: flex;
              align-items: center;
              justify-content: center;
              width: 42px;
              height: 42px;
              border: 1px solid rgb(216, 204, 182);
              border-radius: 50%;
            }

            .img {
              width: 23px;
              height: auto;
            }

            .item + .item {
              margin-top: 10px;
            }
          }
        }
      }
    }
  }
</style>
